package com.kpmg.datalake.common.utils;

import com.kpmg.datalake.common.dynamicdatasource.DBTypeEnum;
import com.kpmg.datalake.common.dynamicdatasource.DatabaseDTO;
import com.kpmg.datalake.common.exception.CustomException;

/**
 * @author Alex.zhao [alex.zhao@kpmg.com]
 * @since Created on azhao6 on 2018-08-21 11:15:05
 */
public class DatabaseUtils {

  /**
   * 分号
   */
  private static final String SEMICOLON = ":";
  /**
   * @ 符号
   */
  private static final String AT = "@";
  /**
   * 斜杠
   */
  private static final String SLASH = "/";

  private DatabaseUtils() {
  }

  /**
   * 解析数据库 URL
   *
   * @param url url
   * @return DatabaseDTO
   */
  public static DatabaseDTO parseUrl(String url) {
    if (url == null || "".equals(url)) {
      return null;
    }
    DatabaseDTO databaseDTO = null;
    //oracle url 解析
    if (url.toLowerCase().contains(DBTypeEnum.ORACLE.getDbType())) {
      int start = url.indexOf(AT);
      if (start > -1) {
        databaseDTO = new DatabaseDTO();
        databaseDTO.setDbType(DBTypeEnum.ORACLE.getDbType());
        int end = url.indexOf(SEMICOLON, start + AT.length());
        databaseDTO.setIp(url.substring(start + AT.length(), end));
        start = end + SEMICOLON.length();
        String spiltFlag = url.indexOf(SEMICOLON, start) > -1 ? SEMICOLON : SLASH;
        end = url.indexOf(spiltFlag, start);
        databaseDTO.setPort(url.substring(start, end));
        databaseDTO.setDbName(url.substring(end + spiltFlag.length()));
      }
    } else {
      throw new CustomException("不支持的数据库url解析");
    }
    return databaseDTO;
  }


}
